package org.csu.jpetstoreagain.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.jpetstoreagain.domain.Account;
import org.csu.jpetstoreagain.domain.Product;
import org.csu.jpetstoreagain.domain.Profile;
import org.csu.jpetstoreagain.persistence.AccountMapper;
import org.csu.jpetstoreagain.persistence.ProfileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountService {
@Autowired
    private AccountMapper accountMapper;
@Autowired
    private ProfileMapper profileMapper;

    //通过username查找账号
    public Account getAccount(String username) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid", username);
        Account account = accountMapper.selectOne(queryWrapper);
        return account;
    }

    //通过用户名密码获得账户
    public Account getAccount(String username, String password) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", username).eq("password", password);
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null) {
            return null;
        } else {
            return account;

        }


    }
    public Profile getProfile(String username){
        QueryWrapper<Profile> queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid", username);
        Profile profile = profileMapper.selectOne(queryWrapper);
        return profile;
    }

    public void insertAccount(Account account,String languagePreference,String favouriteCategoryId,int listOption,int bannerOption) {
        //插入account
        accountMapper.insert(account);
        //插入profile
        Profile profile = new Profile();
        profile.setUserid(account.getUserid());
        profile.setLangpref(languagePreference);
        profile.setFavcategory(favouriteCategoryId);
        profile.setMylistopt(listOption);
        profile.setBanneropt(bannerOption);
        profileMapper.insert(profile);

    }

    public void updateAccount(Account account,Profile profile) {
        UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userid", account.getUserid());
        accountMapper.update(account, updateWrapper);
        UpdateWrapper<Profile> updateWrapper2 = new UpdateWrapper<>();
        updateWrapper2.eq("userid", profile.getUserid());
        profileMapper.update(profile, updateWrapper2);
    }
}
